<template>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <el-button type="primary" plain @click="addRole()">添加角色</el-button>
        <el-table stripe border :data="rolesList">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <!-- 通过 for 循环 嵌套渲染二级权限 -->
                  <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id"><el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col><el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false"><el-button type="primary" icon="el-icon-edit" size="medium" @click="modifyRoleById(scope.row.id)">编辑</el-button>
              </el-tooltip>

              <el-tooltip effect="dark" content="删除" placement="top"><el-button type="danger" icon="el-icon-delete" size="medium" @click="removeRoleById(scope.row.id)">删除</el-button>
              </el-tooltip>

              <el-tooltip effect="dark" content="分配权限" placement="top"><el-button type="warning" icon="el-icon-setting" size="medium" @click="allotPower(scope.row)">分配权限</el-button>
              </el-tooltip>
            </template>
          </el-table-column>

        </el-table>
      </el-card>

      <el-dialog
        title="分配权限"
        :visible.sync="allotPowerDialog"
        width="55%"
        @close="allotPowerDialogClosed()">
        <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all
          :default-checked-keys="defkeys"
          ref="treeRef"
          node-key="id"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="allotPowerDialog = false">取 消</el-button>
          <el-button type="primary" @click="allotPowerSure()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoledDalogVisible"
        width="25%">
        <el-form label-width="80px" :model="addRoleInfo">
          <el-form-item label="角色名称">
            <el-input v-model="addRoleInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addRoleInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoledDalogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureAddRole()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色 -->
      <el-dialog
        title="修改角色"
        :visible.sync="modRoledDalogVisible"
        width="30%">
        <el-form label-width="80px" :model="modRoleInfo">
          <el-form-item label="角色名称">
            <el-input v-model="modRoleInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="modRoleInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modRoledDalogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureModRole()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      allotPowerDialog: false,
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defkeys: [],
      roleId: '',
      addRoledDalogVisible: false,
      addRoleInfo: {},
      modRoledDalogVisible: false,
      CurrentModRoleId: 0,
      modRoleInfo: {}
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      let res = await this.$http.get('roles')
      // console.log(res)
      if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
      if (res.data.meta.status === 200) {
        this.rolesList = res.data.data
        this.$message.success(res.data.meta.msg)
      }
    },
    // 根据Id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      // this.getRolesList()
      role.children = res.data
      this.$message.success(res.meta.msg)
    },
    async allotPower(role) {
      let res = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
      if (res.data.meta.status === 200) {
        this.rightsList = res.data.data
        // console.log(this.rightsList)
      }

      this.getLeafKeys(role, this.defkeys)
      this.roleId = role.id
      this.allotPowerDialog = true
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        return this.getLeafKeys(item, arr)
      })
    },
    allotPowerDialogClosed() {
      this.defkeys = []
    },
    async allotPowerSure() {
      // console.log(this)
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      let res = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
      if (res.data.meta.status === 200) {
        this.getRolesList()
        this.allotPowerDialog = false
        this.$message.success(res.data.meta.msg)
      }
    },
    //添加角色
    addRole() {
      this.addRoledDalogVisible = true
    },
    async sureAddRole () {
      let res = await this.$http.post(`roles`, this.addRoleInfo)
      // console.log(res)
      if (res.data.meta.status !== 201) return this.$message.error(res.data.meta.msg)
      this.$message.success(res.data.meta.msg)
      this.addRoledDalogVisible = false
      this.getRolesList()
    },
    //修改角色信息
    async modifyRoleById(id) {
      // console.log(id)
      this.CurrentModRoleId = id
      let res = await this.$http.get(`roles/${id}`)
      // console.log(res)
      this.modRoleInfo = res.data.data
      this.modRoledDalogVisible = true
    },
    async sureModRole() {
      let res = await this.$http.put(`roles/${this.CurrentModRoleId}`, this.modRoleInfo)
      // console.log(res)
      if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
      this.$message.success(res.data.meta.msg)
      this.modRoledDalogVisible = false
      this.getRolesList()
    },
    //删除角色
    removeRoleById(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let res = await this.$http.delete(`roles/${id}`)
        //  console.log(res)
        if (res.data.meta.status !== 200) return this.$message.error(res.data.meta.msg)
        this.$message.success(res.data.meta.msg)
        this.getRolesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
